package com.renchunlin.topmenubarview.utils

import android.content.Context
import android.content.res.Resources
import android.util.DisplayMetrics
import android.util.TypedValue

/*
 * class title: 
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/5/13.
 * PS: Not easy to write code, please indicate.
 */
class SizeUtils {
    companion object {
        fun dip2px(context: Context, dpValue: Float): Int {
            val scale: Float = context.getResources().getDisplayMetrics().density
            return (dpValue * scale + 0.5f).toInt()
        }

        fun px2dip(context: Context, pxValue: Float): Int {
            //获取当前手机的像素密度
            val scale: Float = context.getResources().getDisplayMetrics().density
            return (pxValue / scale + 0.5f).toInt() //四舍五入取整
        }

        /**
         * 描述：sp转换为px.
         *
         * @param context the context
         * @param spValue the sp value
         * @return sp值
         */
        fun sp2px(context: Context?, spValue: Float): Float {
            val mDisplayMetrics: DisplayMetrics = getDisplayMetrics(context)
            return applyDimension(
                TypedValue.COMPLEX_UNIT_SP,
                spValue,
                mDisplayMetrics
            )
        }

        /**
         * 描述：px转换为sp.
         *
         * @param context the context
         * @param pxValue the sp value
         * @return sp值
         */
        fun px2sp(context: Context?, pxValue: Float): Float {
            val mDisplayMetrics: DisplayMetrics = getDisplayMetrics(context)
            return pxValue / mDisplayMetrics.scaledDensity
        }

        /**
         * 获取屏幕尺寸与密度.
         *
         * @param context the context
         * @return mDisplayMetrics
         */
        fun getDisplayMetrics(context: Context?): DisplayMetrics {
            val mResources: Resources = if (context == null) {
                Resources.getSystem()
            } else {
                context.resources
            }
            return mResources.displayMetrics
        }

        /**
         * TypedValue官方源码中的算法，任意单位转换为PX单位
         *
         * @param unit    TypedValue.COMPLEX_UNIT_DIP
         * @param value   对应单位的值
         * @param metrics 密度
         * @return px值
         */
        fun applyDimension(
            unit: Int, value: Float,
            metrics: DisplayMetrics
        ): Float {
            when (unit) {
                TypedValue.COMPLEX_UNIT_PX -> return value
                TypedValue.COMPLEX_UNIT_DIP -> return value * metrics.density
                TypedValue.COMPLEX_UNIT_SP -> return value * metrics.scaledDensity
                TypedValue.COMPLEX_UNIT_PT -> return value * metrics.xdpi * (1.0f / 72)
                TypedValue.COMPLEX_UNIT_IN -> return value * metrics.xdpi
                TypedValue.COMPLEX_UNIT_MM -> return value * metrics.xdpi * (1.0f / 25.4f)
            }
            return 0f
        }
    }
}